import { _decorator, Component, Node, Label, Color, randomRangeInt, Sprite, AudioClip } from 'cc';
import { SSS_Consts } from "../../Script/Data/SSS_Consts";
import { bdlMgr } from "../../Script/Manager/BundleManager_S";
import SSS_ShuaiFunction from "../../Script/Utils/SSS_ShuaiFunction";
import { SSS_AudioManager } from '../../Script/Manager/SSS_AudioManager';

const { ccclass, property } = _decorator;

@ccclass('CircleTheCatGrid')
export default class CircleTheCat_Grid extends Component {
    @property({ type: Node, tooltip: "格子父节点" })
    bgNode: Node | null = null;
    @property(Label)
    label_pos: Label | null = null;
    @property(Node)
    catNode: Node | null = null; // 拖入Cat子节点
    row: number = 0;
    col: number = 0;
    gameManager: any = null;
    isBlocked: boolean = false;
    normalColor: Color = Color.WHITE;
    blockedColor: Color = Color.GRAY;
    切换猫动作() {
        SSS_ShuaiFunction.SetAllChildrenAtive(this.catNode, false);
        let r = randomRangeInt(0, this.catNode.children.length);
        this.catNode.children[r].active = true;
    }
    init(row: number, col: number, gameManager: any) {
        this.row = row;
        this.col = col;
        this.gameManager = gameManager;
        this.isBlocked = false;
        this.updateState();
        this.showCat(false);

        this.label_pos.string = `${this.row},${this.col}`;
    }
    onLoad() {
        this.node.on(Node.EventType.TOUCH_END, this.onClick, this);
        this.updateState();
        this.showCat(false);
    }
    onClick() {
        if (!this.isBlocked && this.gameManager) {
            let name = `tile click`;
            let audio_root = `audio/${name}`;
            bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, audio_root, AudioClip).then(res => {
                SSS_AudioManager.Instance.playSFX(res, false);
            });


            this.gameManager.onCellClicked(this.row, this.col);
        }
    }
    setBlocked() {
        this.isBlocked = true;
        this.updateState();
    }
    updateState() {
        if (this.isBlocked) {
            this.bgNode.getComponent(Sprite).color = this.blockedColor;
        } else {
            this.bgNode.getComponent(Sprite).color = this.normalColor;
        }
    }
    showCat(show: boolean) {
        if (this.catNode) {
            this.catNode.active = show;
        }
    }
}
